package com.forcht.ioc.factory;

import com.forcht.ioc.BeanDefinition;
import com.forcht.ioc.BeanReference;
import com.forcht.ioc.PropertyValue;

import java.lang.reflect.Field;

/**
 * Created by forcht on 2018/4/17.
 * 可自动装配的bean工厂
 */
public class AutowireCapableBeanFactory extends AbstractBeanFactory {
    @Override
    protected Object doCreateBean(BeanDefinition beanDefinition) throws Exception {
        Object bean = createBeanInstance(beanDefinition);
        beanDefinition.setBean(bean);
        applyPropertyValues(bean, beanDefinition);
        return bean;
    }

    public Object createBeanInstance(BeanDefinition beanDefinition) throws Exception {
        return beanDefinition.getBeanClass().newInstance();
    }

    public void applyPropertyValues(Object bean, BeanDefinition beanDefinition) throws Exception {
        for (PropertyValue p : beanDefinition.getPropertyValues().getPropertyValues()) {
            Field field = bean.getClass().getDeclaredField(p.getName());
            field.setAccessible(true);
            Object value = p.getValue();
            if(value instanceof BeanReference){
                BeanReference reference = (BeanReference) value;
                value=getBean(reference.getName());
            }
            field.set(bean,value);
        }
    }
}
